package com.example.mythealthapp.me

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil

import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.mythealthapp.R
import com.example.mythealthapp.databinding.FragmentMeBinding
import com.example.mythealthapp.users.DBHelper
import com.example.mythealthapp.users.User
import kotlinx.android.synthetic.main.fragment_me.*


class MeFragment : Fragment() {
    private lateinit var helper: DBHelper

    lateinit var user: User
    lateinit var phone: String
    lateinit var dataBinding: FragmentMeBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        helper = DBHelper(context, "User", 1)
        phone = requireActivity().intent.getStringExtra("userphone").toString()
        user = findUser(phone)

    }


    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        dataBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_me, container, false)
        return dataBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        me_recl.adapter=MeAdapter(user)
        me_recl.layoutManager=LinearLayoutManager(context)
    }

    @SuppressLint("Range")
    private fun findUser(userphone: String): User {
        val db = helper.readableDatabase

        val cursor = db.query(
            User.TABLE,
            null,
            User.U_phone + "=?",
            arrayOf(userphone),
            null,
            null,
            null,
            null
        )
        return if (cursor.moveToFirst()) {
            User(
                cursor.getString(cursor.getColumnIndex(User.U_name)),
                cursor.getString(cursor.getColumnIndex(User.U_phone)),
                "",
                cursor.getInt(cursor.getColumnIndex(User.U_avatar)),
                cursor.getInt(cursor.getColumnIndex(User.U_gender)),
                cursor.getLong(cursor.getColumnIndex(User.U_addtime)),
                cursor.getInt(cursor.getColumnIndex(User.U_level))
            )
        } else {
            User("","","",0,0,0,0,)
        }
    }

}
